import {
    createSlice
} from "@reduxjs/toolkit";
import {
    deleteHospitalSetBatchRemove,
    deleteHospitalSetById,
    getHospitalSet,
    getHospitalSetLockById,
    postHospitalSetSave,
    putHospitalSetUpdate
} from "@/api/hosp";
import {useSelector} from "react-redux";
import {upLoading, upPageInfo} from "@/store/slices/common";
import React from "react";

const hospSlice = createSlice({
    name:"hosp",
    initialState:{
        hospitalSetList:[],// 医院设置列表
        params:{}
    },
    reducers:{

        changeParams(state,{payload}){
            state.params = payload;
        },
        upHospitalSetList(state,{payload}){
            state.hospitalSetList = payload;
        }
    }
})
export const {upHospitalSetList,changeParams} = hospSlice.actions;
// 暴露异步action:调用医院设置列表信息
export const getHospitalSetAsync = (page:number,limit:number)=>{
    return async (dispatch:any,getState:any)=>{
        dispatch(upLoading(true));
        const result = await getHospitalSet(page,limit,getState().hosp.params);
        dispatch(upHospitalSetList(result.data.records));
        dispatch(upPageInfo({
            current:result.data.current,
            pageSize:result.data.size,
            total:result.data.total
        }))
        dispatch(upLoading(false));
    }
}

// 更改锁定状态
export const getHospitalSetLockByIdAsync = (id:number,status:number)=>{
    return async (dispatch:any,getState:any)=>{
        await getHospitalSetLockById(id,status);
        // const {pageInfo:{current,pageSize}} = getState().common;
        const {current,pageSize} = getState().common.pageInfo;
        await dispatch(getHospitalSetAsync(current,pageSize));
    }
}

// 添加医院设置
export const postHospitalSetSaveAsync = (body:any)=>{
    return async (dispatch:any,getState:any)=>{
        let result ;
        if(body.id){
            // 修改
            result = await putHospitalSetUpdate(body);
        }else{
            // 添加
            result = await postHospitalSetSave(body);// 添加医院
        }

        const {current,pageSize} = getState().common.pageInfo;
        await dispatch(getHospitalSetAsync(current,pageSize));// 更新设置
        return result;
    }
}
export const deleteHospitalSetByIdAsync = (id:number)=>{
    return async (dispatch:any,getState:any)=>{
        await deleteHospitalSetById(id);
        const {current,pageSize} = getState().common.pageInfo;
        await dispatch(getHospitalSetAsync(current,pageSize));// 更新设置
    }
}

// 批量删除异步action
export const deleteHospitalSetBatchRemoveAsync = (data:React.Key[])=>{
    return async (dispatch:any,getState:any)=>{
        await deleteHospitalSetBatchRemove(data);
        const {current,pageSize} = getState().common.pageInfo;
        await dispatch(getHospitalSetAsync(current,pageSize));// 更新设置
    }
}
export const useSelectorHosp = ()=>useSelector((state:any)=>state.hosp);
export default hospSlice.reducer;
